import pandas as pd


def github_developers(country):
    # 读取CSV数据
    url = 'https://raw.githubusercontent.com/github/innovationgraph/refs/heads/main/data/developers.csv'
    df = pd.read_csv(url, names=['developers', 'iso2_code', 'year', 'quarter'])

    # 确保'developers'列为数值类型
    df['developers'] = pd.to_numeric(df['developers'], errors='coerce')

    # 获取最新季度
    quarter_lastest = df.tail(1)['quarter'].values[0]

    # 过滤出全球和中国所有年份最新季度的数据
    global_data = df[df['quarter'] == quarter_lastest]
    country_data = df[(df['iso2_code'] == country) & (df['quarter'] == quarter_lastest)]

    # 分析每年的开发者数量
    global_yearly_data = global_data.groupby('year')['developers'].sum().reset_index()
    country_yearly_data = country_data.groupby('year')['developers'].sum().reset_index()

    # 合并两个DataFrame以方便计算比例
    merged_df = global_yearly_data.merge(country_yearly_data, on='year', suffixes=('_global', '_country'))
   
    # 计算增长率
    merged_df['global_growth_rate'] = merged_df['developers_global'].pct_change() * 100
    merged_df['country_growth_rate'] = merged_df['developers_country'].pct_change() * 100


    # 计算占比
    merged_df['country_percentage'] = (merged_df['developers_country'] / merged_df['developers_global']) * 100

    return merged_df

def main():
    # 存在结果地址
    output_file = './data/developers.xlsx'
    # 获取开发者数据
    data = github_developers('CN')
    data.to_excel(output_file, index=False)
    print(data)
    print('已成功导入文件')

if __name__ == '__main__':
    main()